package com.mapapp.flutter_mapapp.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.SizeUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mapapp.flutter_mapapp.R;
import com.mapapp.flutter_mapapp.adapter.AddPictureAdapter;
import com.mapapp.flutter_mapapp.adapter.NewDataStepAdapter;
import com.mapapp.flutter_mapapp.bean.HistoryDetail;
import com.mapapp.flutter_mapapp.bean.ProcessBean;
import com.mapapp.flutter_mapapp.http.Url;
import com.mapapp.flutter_mapapp.persenter.HistoryDetailPresenter;
import com.mapapp.flutter_mapapp.util.HorizontalSpaceItemDecoration;
import com.mapapp.flutter_mapapp.util.ImageUtil;
import com.mapapp.flutter_mapapp.util.ToastUtils;
import com.mapapp.flutter_mapapp.view.HistoryDetailViewInterface;
import com.mapapp.flutter_mapapp.widget.TitleBar;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HistoryDetailActivity extends ImmersiveBaseActivity implements HistoryDetailViewInterface {

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.iv_door_photo)
    ImageView ivDoorPhoto;
    @BindView(R.id.step_options)
    TextView stepOptions;
    @BindView(R.id.rv_step)
    RecyclerView rvStep;
    @BindView(R.id.tv_add_remark)
    TextView tvAddRemark;
    @BindView(R.id.et_add_remark)
    TextView etAddRemark;
    @BindView(R.id.tv_add_pictures)
    TextView tvAddPictures;
    @BindView(R.id.rv_add_pictures)
    RecyclerView rvAddPictures;
    @BindView(R.id.tv_play_radio)
    TextView tvPlayRadio;

    private HistoryDetailPresenter presenter;

    private AddPictureAdapter pictureAdapter;
    private final ArrayList<String> imageUrls = new ArrayList<>();
    private final List<String> thumbImageUrls = new ArrayList<>();

    private HistoryDetail historyDetail;

    private NewDataStepAdapter stepAdapter;
    private MediaPlayer mediaPlayer;
    private boolean playSuccessfully;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history_detail);
        ButterKnife.bind(this);

        String opId = getIntent().getStringExtra("opId");

        rvAddPictures.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        rvAddPictures.setNestedScrollingEnabled(false);
        pictureAdapter = new AddPictureAdapter(R.layout.item_add_picture);
        rvAddPictures.addItemDecoration(new HorizontalSpaceItemDecoration(SizeUtils.dp2px(2)));
        pictureAdapter.makeDelGone();
        rvAddPictures.setAdapter(pictureAdapter);

        pictureAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, PreviewPictureActivity.class);
                intent.putStringArrayListExtra("images", imageUrls);
                intent.putExtra("current", position + 1);
                startActivity(intent);
            }
        });

        ivDoorPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (historyDetail != null) {
                    HistoryDetail.PhotoBean photo = historyDetail.getPhoto();
                    if (photo != null && photo.getTop_photo() != null) {
                        Intent intent = new Intent(mContext, PreviewPictureActivity.class);
                        String photo_folder = photo.getPhoto_folder();
                        ArrayList<String> strings = new ArrayList<>();
                        strings.add(Url.BASE_URL + "/common/output/image/" +
                                photo_folder + "/" + photo.getTop_photo() + "/ygf");
                        intent.putStringArrayListExtra("images", strings);
                        intent.putExtra("current", 1);
                        startActivity(intent);
                    }
                }
            }
        });

        rvStep.setLayoutManager(new LinearLayoutManager(mContext));
        stepAdapter = new NewDataStepAdapter(R.layout.item_step_new_data, null);
        rvStep.setAdapter(stepAdapter);

        titleBar.getIvBack().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        presenter = new HistoryDetailPresenter(this, this, lifecycleSubject);

        presenter.getHistory(opId);
    }

    @Override
    public void showHistoryDetail(HistoryDetail historyDetail) {
        if (historyDetail != null) {
            this.historyDetail = historyDetail;
            HistoryDetail.PhotoBean photo = historyDetail.getPhoto();
            List<String> others = photo.getOthers();
            if (others != null && !others.isEmpty()) {
                generateImageUrl(others, photo.getPhoto_folder());
                pictureAdapter.setNewData(thumbImageUrls);
            }

            ProcessBean processBean = new ProcessBean();
            processBean.setState(historyDetail.getState());
            processBean.setProcessName(historyDetail.getProcess_name());
            processBean.setProcessOrder(historyDetail.getProcess_order());
            List<ProcessBean> processBeans = new ArrayList<>();
            processBeans.add(processBean);
            stepAdapter.setHistoryDetailStep(true);
            stepAdapter.setNewData(processBeans);

            titleBar.getTitleBarCenter().setText(historyDetail.getRegion_name());

            etAddRemark.setText(historyDetail.getComment());

            ImageUtil.loadImage(Url.BASE_URL + "/common/output/image/" +
                    photo.getPhoto_folder() + "/" + photo.getTop_photo() + "/ygf", ivDoorPhoto);

        }
    }

    private void generateImageUrl(List<String> list, String dirName) {
        imageUrls.clear();
        thumbImageUrls.clear();
        for (String s : list) {
            if (s != null && !s.startsWith("top_")) {
                String prefix = Url.BASE_URL + "/common/output/image/" +
                        dirName + "/" + s + "/";
                imageUrls.add(prefix + "ygf");
                thumbImageUrls.add(prefix + "thumb");
            }
        }
    }

    @OnClick(R.id.tv_play_radio)
    public void onViewClicked() {
        if (historyDetail == null || historyDetail.getRadio() == null || historyDetail.getRadio().getRadio_name() == null) {
            ToastUtils.showMessage(mContext, "没有音频文件");
            return;
        }

        if (mediaPlayer == null) {
            mediaPlayer = new MediaPlayer();
        }

        if (playSuccessfully) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
                tvPlayRadio.setText("已暂停");
            } else {
                mediaPlayer.start();
                tvPlayRadio.setText("正在播放");
            }
            return;
        }

        final ProgressDialog pd = new ProgressDialog(mContext);
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                pd.setMessage("正在加载");
                pd.show();
            }
        });

        try {
            mediaPlayer.setDataSource(Url.BASE_URL + "/common/output/radio/" + historyDetail.getRadio().getRadio_folder() + "/" + historyDetail.getRadio().getRadio_name());
            mediaPlayer.prepare();
            mediaPlayer.start();
            playSuccessfully = true;
            tvPlayRadio.setText("正在播放");
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtils.showMessage(mContext, "播放失败");
        }

        new Handler().post(new Runnable() {
            @Override
            public void run() {
                pd.dismiss();
            }
        });

    }


    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            tvPlayRadio.setText("已暂停");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mediaPlayer != null) {
            tvPlayRadio.setText("正在播放");
            mediaPlayer.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
    }
}
